package cn.hgpu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录认证过滤器
 *
 *  将未登录请求拦截在系统外面
 */
@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
    private String[] urls= {"login.jsp","login"};

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //白名单放行
        //获取请求路径
        String requestURI = request.getRequestURI();
        for (String url : urls) {
            if(requestURI.contains(url)){
                //如果是白名单中的URL，则放行
                filterChain.doFilter(request, response);
                return;
            }
        }

        //登录状态判断
        Object o = request.getSession().getAttribute("admin");
        if(o==null){
            //没登录，打回登录页面
            response.sendRedirect("/login.jsp");
            return;
        }

        //放行
        filterChain.doFilter(request, response);
    }
}